package Cashier;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class RetailSys extends HttpServlet {//Leong Vai Cheong

	private static final long serialVersionUID = 1L;
	
	private static int No = 10000;
	private int orderCount;
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)	throws ServletException, IOException {
		
		HttpSession session = req.getSession();
		
    	String clear =  req.getParameter("clear");
    	String reflash = req.getParameter("reflash");
    	String code = req.getParameter("CODE");
    	String purchaseQty = req.getParameter("PurchaseQty"); 
    	String buff_payment = req.getParameter("payment");
    	String paymentway = req.getParameter("paymentway");
    	String MEMBER = req.getParameter("MEMBER");
    	
    	
		String dbName = "retail";
		String tbName = "product";		
		String jdbcStr = "jdbc:h2:~/" + dbName;
		
		String tbPrimaryKey = "productid";	
		
		List<Item> rs_items = null;
		List<Item> items = null;	
		double payment = 0, total = 0, subtotal = 0;
		Double buff_total = null;
		Integer orderNo = null;
		String operator = null;
		
		if( !dbName.isEmpty() && !tbName.isEmpty() )
		try {
			Class.forName("org.h2.Driver");
			Connection con = DriverManager.getConnection(jdbcStr,"sa","");
			
			String  selectSQL = "select * from " + tbName + " where " +tbPrimaryKey+ " = ?";
			PreparedStatement ps =  con.prepareStatement(selectSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

			ps.setString(1, code);
			ResultSet rs = ps.executeQuery();
			
			rs_items = Item.getData(rs);
			
			if (clear != null && clear.equals("1")) 
				session.invalidate();			
			else
			{
				items = (List<Item>)session.getAttribute("items");				
				buff_total = (Double)session.getAttribute("total");
				orderNo = (Integer)session.getAttribute("orderNo");
				operator = (String)session.getAttribute("operator");
			}
			
			if (items == null)						
				items = new ArrayList<Item>();
			
			if (buff_total != null)
				total = buff_total;
			
			if (buff_payment != null)
				payment = Double.parseDouble(buff_payment);
								
				
			Item it = null;
			int same = 0, qty = 0;
					
			for ( int i = 0;  rs_items.size() > i; i++ ) {	
				it = (Item) rs_items.get(i);
																									
				for (int j = 0; items.size() > j; j++) {
														
						if (items.get(j).getBarcode().equals(it.getBarcode())) {
							
							qty = items.get(j).getPurchaseQty() + 1;							
							items.get(j).setPurchaseQty(qty);							
							subtotal = items.get(j).getPrice() * qty;							
							items.get(j).setSubtotal(subtotal);							
							total += items.get(j).getPrice();							
							same = 1;							
						} 													
				}
				
				if(same != 1) {
					items.add(it);
					total += it.getSubtotal();
				}
				
				session.setAttribute("items", items);
			}
			

			if (reflash != null && purchaseQty != null) {						
				qty = Integer.parseInt(purchaseQty);
				total = 0; 
				for (int j = 0; items.size() > j; j++) {
					
					if (items.get(j).getBarcode().equals(reflash)) {
							
						items.get(j).setPurchaseQty(qty);		
						subtotal = items.get(j).getPrice() * qty;
						items.get(j).setSubtotal(subtotal);							
						session.setAttribute("items", items);							
					}	
						total += items.get(j).getSubtotal();
				}
			}
								
			if (clear == null) {
				session.setAttribute("total", total);
				
				if (payment > 0) {
					double balance = payment-total;
					
					if (balance >= 0) {					
						
						if (paymentway == null || MEMBER == null) {
							paymentway = "cash";
						}
						else {	
								if(paymentway.equals("1"))
									paymentway = "cash";
								else 
									if(paymentway.equals("2"))
										paymentway = "CreditCard";
									else 
										paymentway = MEMBER;
						}
						
						Date date = new Date(System.currentTimeMillis());
						DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,Locale.CHINA);
						String dt = df.format(date);				
						
						String tbName1 = "orders";					
						String insertSQL = "insert into "+tbName1+" values(?,?,?,?,?,?,?,?,?,?,?)";						
						PreparedStatement ps1 =  con.prepareStatement(insertSQL);
						
						int n = 0;
						for (int i = 0; i < items.size(); i++) {
							ps1.setString(1, String.valueOf(No));
							ps1.setString(2, items.get(i).getBarcode());
							ps1.setString(3, items.get(i).getDescription());
							ps1.setDouble(4, items.get(i).getPrice());
							
							ps1.setInt(5, items.get(i).getPurchaseQty());
							ps1.setString(6, paymentway);
							
							ps1.setDouble(7, items.get(i).getSubtotal());
							ps1.setDouble(8, payment);
							ps1.setDouble(9, balance);
							ps1.setString(10,operator);
							ps1.setString(11, dt);
							
							n = ps1.executeUpdate();
							
							if(n > 0) {
								String updateSQL = "update " + tbName + " set QUANTITY=" + "'"+(items.get(i).getInventoryQty()-items.get(i).getPurchaseQty())+"'" 
													+ " where PRODUCTID="+ "'"+items.get(i).getBarcode()+"'";
								ps = con.prepareStatement(updateSQL);
								int k = ps.executeUpdate();			
							}
						}
						session.invalidate();
					} 
					else {
							session.setAttribute("payment", payment);
							session.setAttribute("balance", balance);
					}
				}

					if (orderNo == null) {
						session.setAttribute("orderNo", ++No);
					}

					if (operator == null) {
						operator = "Max";
						session.setAttribute("operator", operator);
					}

			}
								
				RequestDispatcher dispatcher = req.getRequestDispatcher("/showProduct.jsp");
				dispatcher.forward(req, resp);
		} 
		catch (ClassNotFoundException e) {
			e.printStackTrace();	
		} 
		catch (SQLException e) {
			e.printStackTrace();			
		}
		
		/*
		List<Cashier> allOrders = new ArrayList<Cashier>();
		
		
		Cashier.setItemList(items);//Enter items description
		String[] operators = {"Gigi"};
		
		for (int n = 0; n < operators.length; n++) {
			Cashier cashier = new Cashier();
			cashier.setOperator(operators[n]);//Enter the cashier name
			
			for (int i = 0; i < items.length; i++) {
				int k = rd.nextInt(items.length);
				cashier.addItemToOrderList(barcodes[k]);//Use items barcode input order information
			}
			allOrders.add(cashier);
		}
		
		//for(int i = 0; i < allOrders.size(); i++ ){
			//allOrders.get(i).printReceipt();//The output orders items information
			//System.out.println();
			
		//}

		System.out.println("Extant Item List:");		
		Cashier.printItemsInfo(Cashier.getItemList(), Cashier.getItemList().length);//The output surplus items information 
*/
	}
}